package gofunc

import (
	"fmt"
	"log"
	"sync"
	"time"
)

func func1() {
	//log.Println("func1 start ")
	//go func2()
	//time.Sleep(time.Second * 5)
	//log.Println("func1 end ")
	log.Println("func1")
	time.Sleep(time.Second * 2)
}

func func2() {
	log.Println("func2")
	time.Sleep(time.Second * 2)
}

func worker(f func(), wg *sync.WaitGroup, done chan bool) {
	defer wg.Done() // 确保goroutine结束时从waitGroup中减去计数

	for {
		select {
		case <-done:
			fmt.Printf("Worker received done signal\n")
			return // 当接收到done信号时，函数返回，wg计数减一
		default:
			fmt.Printf("Worker is doing some work\n")
			f()
		}
	}
}

func Test() {
	var wg sync.WaitGroup
	done := make(chan bool)
	wg.Add(1)
	go worker(func() {
		func1()
	}, &wg, done)

	wg.Add(1)
	go worker(func() {
		func2()
	}, &wg, done)

	// 等待一段时间后通知所有goroutine退出
	go func() {
		time.Sleep(8 * time.Second)
		fmt.Println("Main: Now closing all the workers")
		close(done) // 关闭channel，通知所有worker退出
	}()

	// 等待所有goroutine结束
	wg.Wait()
	fmt.Println("Main: All workers are closed")
}
